﻿using System.Security.Principal;
using System.Web.Mvc;
using Smarly.Bussines.Membership;

namespace Smarly.Web.ViewEngine
{
	public class SmarlyViewEngine : RazorViewEngine
	{
		protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
		{
			partialPath = GetRolePath(controllerContext, partialPath);
			return base.CreatePartialView(controllerContext, partialPath);
		}

		protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
		{
			viewPath = GetRolePath(controllerContext, viewPath);
			return base.CreateView(controllerContext, viewPath, masterPath);
		}

		private string GetRolePath(ControllerContext controllerContext, string path)
		{
			var principal = controllerContext.HttpContext.User as SmarlyPrincipal;
			if (principal == null || !principal.Identity.IsAuthenticated)
				return path;

			string extention = string.Empty;
			string tempPath = string.Empty;

			foreach (var ext in base.FileExtensions)
			{
				if (path.EndsWith(ext))
				{
					extention = ext;
					tempPath = path.Substring(0, path.Length - ext.Length);
					break;
				}
			}

			if (string.IsNullOrWhiteSpace(extention))
				return path;

			foreach (var role in principal.GetUserRoles())
			{
				string virtualPath = tempPath + role + "." + extention;
				if (FileExists(controllerContext, virtualPath))
				{
					return virtualPath;
				}
			}

			return path;
		}
	}
}